<?php
namespace Home\Controller;
use Think\Controller;
class IndexController extends BaseController {
	public function __construct(){
		parent::__construct();
        $this->login_user = $this->checkLogin(false);
        if(!$this->login_user){
            $this->redirect('Home/Passport/login');
        }
	}

    /**
     * ps ：首页
     * Time：2016/10/14 10:23:09
     * @author liuxin
     * @param 参数类型
     * @return 返回值类型
    */
    public function index(){
        $Project = D('Project');
        if($this->login_user['username'] == 'admin'){
            $data = $Project -> select();
        }
        else{
            $data = $Project -> where("project_type = 'public'") -> select();
            $projects = M('ProjectUser')->where(['user_id'=>$this->login_user['user_id']])->field('project_id')->select();
            foreach ($projects as $k => $v) {
                $tmp = $Project->where(['project_type'=>'private','project_id'=>$v['project_id']])->find();
                if($tmp){
                    $data[] = $tmp;
                }
            }
        }

        $this->assign('projects',$data);
        $this->assign('active_menu','index');
    	$this->assign('bread','所有项目');
    	$this->assign('login_user',$this->login_user);
        $this->display();
    }

    /**
     * ps ：创建项目
     * Time：2016/10/14 10:22:58
     * @author liuxin
     * @param 参数类型
     * @return 返回值类型
    */
    public function createProject(){
    	if(!IS_POST){
            $this->assign('active_menu',['one'=>'project','two'=>'create']);
    		$this->assign('bread','创建项目');
    		$this->display();
    	}
    	else{
    		$Project = D('Project');
            $postdata = I('post.');
            $postdata['creator_id'] = $postdata['creator_id'] ? $postdata['creator_id'] : $this->login_user['user_id'];
    		if($Project->create()){
    			$result = $Project->add($postdata);
	            if($result) {
                    $projectUser = M('ProjectUser');
                    $projectUser->add(['project_id'=>$result,'user_id'=>$this->login_user['user_id'],'auth'=>'owner']);
                	$this->ajaxReturn(['success'=>true,'msg'=>'项目创建成功！','url'=>U('Home/Index/index')]);exit;
	            }else{
                	$this->ajaxReturn(['success'=>false,'msg'=>'项目创建失败！']);exit;
	            }
    		}
    		else{
    			$this->ajaxReturn($Project->getError());
    		}
    	}
    }

    /**
     * ps ：我的项目
     * Time：2016/10/14 10:25:26
     * @author liuxin
     * @param 参数类型
     * @return 返回值类型
    */
    public function myProject(){
        $Project = D('Project');
        $projects = M('ProjectUser')->where(['user_id'=>$this->login_user['user_id']])->field('project_id')->select();
        foreach ($projects as $k => $v) {
            $data[] = $Project->where(['project_id'=>$v['project_id']])->find();
        }

        $this->assign('projects',$data);
        $this->assign('active_menu',['one'=>'project','two'=>'my']);
        $this->assign('bread','我的项目');
        $this->assign('login_user',$this->login_user);
        $this->display();
    }

    /**
     * ps ：个人信息
     * Time：2016/10/21 13:18:14
     * @author liuxin
     * @param 参数类型
     * @return 返回值类型
    */
    public function editUserinfo(){
        if(!IS_POST){
            $user = M('User')->where(['user_id'=>$this->login_user['user_id']])->find();

            $this->assign('active_menu',['one'=>'account','two'=>'info']);
            $this->assign('bread','个人资料');
            $this->assign('user',$user);
            $this->assign('login_user',$this->login_user);
            $this->display();
        }
        else{
            $postdata = I('post.');
            $user = array(
                'user_id' => $this->login_user['user_id'],
                'nickname' => $postdata['nickname'],
                'sex' => $postdata['sex'],
                'mobile' => $postdata['mobile'],
                'email' => $postdata['email'],
                'qq' => $postdata['qq'],
                'headurl' => $postdata['headurl'],
            );
            // dump($user);die;
            if(M('User')->save($user) !== false){
                $this->ajaxReturn(['success'=>true,'msg'=>'修改成功！','url'=>U('Home/Index/editUserinfo')]);exit;
            }
            else{
                $this->ajaxReturn(['success'=>false,'msg'=>'修改失败！']);exit;
            }
        }
    }

    /**
     * ps ：修改密码
     * Time：2016/10/21 13:20:23
     * @author liuxin
     * @param 参数类型
     * @return 返回值类型
    */
    public function modifyPwd(){
        if(!IS_POST){
            $this->assign('active_menu',['one'=>'account','two'=>'modifypwd']);
            $this->assign('bread','修改密码');
            $this->assign('login_user',$this->login_user);
            $this->display();
        }
        else{
            $postdata = I('post.');
            $old_pwd = $postdata['old_password'];
            $new_pwd = $postdata['password'];
            $confirm_pwd = $postdata['confirm_pwd'];

            if($old_pwd == '' || $new_pwd == '' || $confirm_pwd == ''){
                $this->ajaxReturn(['success'=>false,'msg'=>'密码不能为空！']);exit;
            }
            if($old_pwd == $new_pwd){
                $this->ajaxReturn(['success'=>false,'msg'=>'新密码不能和原密码一致！']);exit;
            }
            if($new_pwd != $confirm_pwd){
                $this->ajaxReturn(['success'=>false,'msg'=>'两次密码输入不一致！']);exit;
            }

            $User = D('User');
            if(!$User->checkPassword($this->login_user['user_id'],$old_pwd)){
                $this->ajaxReturn(['success'=>false,'msg'=>'原密码错误！']);exit;
            }
            if($User->save(['user_id'=>$this->login_user['user_id'],'password'=>md5(base64_encode(md5($new_pwd)).'576hbgh6')]) !== false){
                $this->ajaxReturn(['success'=>true,'msg'=>'修改成功！','url'=>U('Home/Index/modifyPwd')]);exit;
            }
            else{
                $this->ajaxReturn(['success'=>false,'msg'=>'修改失败！']);exit;
            }
        }
    }

    public function signManage(){
        if($this->login_user['username'] != 'admin'){
            $this->message('抱歉，您没有权限',U('Home/Index/index'));exit();
        }

        $User = D('User');
        $Project = M('Project');
        $ProjectSign = M('ProjectSignApply');

        $page_no = I('page_no')?I('page_no'):1;
        $pagesize = 20;

        $filter = [];
        if(I('status')){
            $filter['status'] = I('status');
        }
        // dump($filter);die;

        $data = $ProjectSign->where($filter)->page($page_no,$pagesize)->order('create_time desc')->select();
        $count = $ProjectSign->where($filter)->count();
        $page['count'] = ceil($count/$pagesize);
        $page['current'] = $page_no;

        foreach ($data as $k => &$v) {
            $v['creator'] = $User->getUserName($v['creator_id']);
            if($operator_id){
                $v['operator'] = $User->getUserName($v['operator_id']);
            }
            if($v['create_time']){
                $v['create_time'] = date('Y-m-d H:i:s',$v['create_time']);
            }
            if($v['operate_time']){
                $v['operate_time'] = date('Y-m-d H:i:s',$v['operate_time']);
            }
            switch ($v['status']) {
                case 'progress':
                    $v['status'] = '待审核';
                    break;
                case 'success':
                    $v['status'] = '审核通过';
                    break;
                case 'fail':
                    $v['status'] = '审核未通过';
                    break;
            }
            $v['project_name'] = $Project->where(['project_id'=>$v['project_id']])->field('project_name')->find()['project_name'];
        }

        $this->assign('active_menu',['one'=>'admin','two'=>'sign_apply']);
        $this->assign('bread','修改密码');
        $this->assign('login_user',$this->login_user);
        $this->assign('sign_applys',$data);
        $this->assign('page',$page);
        $this->assign('filter',$filter);
        $this->display();
    }

    public function applyDetail(){
        if(!IS_POST){
            if($this->login_user['username'] != 'admin'){
                $this->message('抱歉，您没有权限',U('Home/Index/index'));exit();
            }
            $ProjectSign = M('ProjectSignApply');
            $apply_id = I('apply_id');
            $ProjectSignApply = $ProjectSign->where(['apply_id'=>$apply_id])->find();

            $file_path = $ProjectSign->where(['apply_id'=>$apply_id])->field('sign_path')->find()['sign_path'];
            //判断文件是否存在 
            if(file_exists($file_path)){ 
                //判断文件是否能打开 
                if($fp=fopen($file_path,"r")){ 
                    $str=""; 
                    for($i=1;! feof($fp);$i++){
                        $str .= '<div class="line"><span class="line-tag">'.$i.'.</span><span class="line-content">'.htmlentities(fgets($fp)). '</div>'; 
                    } 
                }else{ 
                    $str .= "文件不能打开"; 
                } 
            }else{ 
                $str .= "没有这个文件"; 
            } 
            //替换字符 
            // $str=str_replace("\r","",$str); 
            fclose($fp);

            $this->assign('active_menu',['one'=>'admin','two'=>'sign_apply']);
            $this->assign('bread','申请详情');
            $this->assign('apply',$ProjectSignApply);
            $this->assign('signContent',$str);
            $this->display();
        }
        else{
            $postdata = I('post.');
            $ProjectSignApply = M('ProjectSignApply');
            $ProjectSign = M('ProjectSign');
            $apply_info = $ProjectSignApply->where(['apply_id'=>$postdata['apply_id']])->find();
            $ProjectSignApply->startTrans();

            $apply_data = array(
                'apply_id' => $postdata['apply_id'],
                'status' => $postdata['status'],
                'memo' => $postdata['memo'],
                'operate_time' => time(),
                'operator_id' => $this->login_user['user_id'],
            );
            $one = $ProjectSignApply->save($apply_data);
            if(!$one){
                $ProjectSignApply->rollback();
                $this->ajaxReturn(['success'=>false,'msg'=>'修改失败！']);exit;
            }

            if($postdata['status'] == 'success'){
                $sign_data = array(
                    'apply_id' => $postdata['apply_id'],
                    'project_id' => $apply_info['project_id'],
                    'creator_id' => $apply_info['creator_id'],
                    'sign_path' => $apply_info['sign_path'],
                    'create_time' => $apply_info['create_time'],
                );
                if($ProjectSign->where(['project_id' => $apply_info['project_id']])->count()){
                    $two = $ProjectSign->save($sign_data);
                }
                else{
                    $two = $ProjectSign->add($sign_data);
                }
                if(!$two){
                    $ProjectSignApply->rollback();
                    $this->ajaxReturn(['success'=>false,'msg'=>'修改失败！']);exit;
                }
            }
            $ProjectSignApply->commit();
            $this->ajaxReturn(['success'=>true,'msg'=>'修改成功！','url'=>U('Home/Index/applyDetail',['apply_id'=>$postdata['apply_id']])]);exit;
        }
    }

    public function deleteApply(){
        $apply_id = I('apply_id');
        if(M('ProjectSignApply')->where(['apply_id'=>$apply_id])->delete()){
            $this->ajaxReturn(['success'=>true,'msg'=>'删除成功！','url'=>U('Home/Index/signManage')]);exit;
        }
        else{
            $this->ajaxReturn(['success'=>false,'msg'=>'删除失败！']);exit;
        }
    }

    public function signList(){
        $signList = M('ProjectSign')->select();
        $Project = M('Project');
        $Project = M('Project');
        $User = D('User');
        foreach ($signList as $k => &$v) {
            $v['creator'] = $User->getUserName($v['creator_id']);
            $v['create_time'] = date('Y-m-d H:i:s',$v['create_time']);
            $v['project_name'] = $Project->where(['project_id'=>$v['project_id']])->find()['project_name'];
        }

        $this->assign('active_menu',['one'=>'admin','two'=>'signlist']);
        $this->assign('bread','申请详情');
        $this->assign('sign_list',$signList);
        $this->display();
    }

    public function deleteSign(){
        $project_id = I('project_id');
        if(M('ProjectSign')->where(['project_id'=>$project_id])->delete()){
            $this->ajaxReturn(['success'=>true,'msg'=>'删除成功！','url'=>U('Home/Index/signList')]);exit;
        }
        else{
            $this->ajaxReturn(['success'=>false,'msg'=>'删除失败！']);exit;
        }
    }
}